//package com.galen.config;
//
//import com.fasterxml.jackson.databind.ObjectMapper;
//import com.galen.kaptch.KaptchaFilter;
//import com.galen.remember.MyRememberMe;
//import lombok.RequiredArgsConstructor;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.context.annotation.Bean;
//import org.springframework.context.annotation.Configuration;
//import org.springframework.http.MediaType;
//import org.springframework.security.authentication.AuthenticationManager;
//import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
//import org.springframework.security.config.annotation.web.builders.HttpSecurity;
//import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
//import org.springframework.security.core.userdetails.UserDetailsService;
//import org.springframework.security.web.authentication.RememberMeServices;
//import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
//import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
//import org.springframework.security.web.authentication.rememberme.PersistentTokenBasedRememberMeServices;
//import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;
//import org.springframework.security.web.session.HttpSessionEventPublisher;
//import org.springframework.security.web.session.SessionInformationExpiredEvent;
//import org.springframework.security.web.session.SessionInformationExpiredStrategy;
//import org.springframework.session.FindByIndexNameSessionRepository;
//import org.springframework.session.security.SpringSessionBackedSessionRegistry;
//
//import javax.servlet.ServletException;
//import javax.servlet.http.HttpServletResponse;
//import javax.sql.DataSource;
//import java.io.IOException;
//import java.util.HashMap;
//import java.util.Map;
//import java.util.UUID;
//
///**
// * 自定义过滤器实现登陆功能，可作为为Spring security过滤器参考使用
// *
// * @author GalenGao
// * @version Id: SecurityConfig.java, v 0.1 2022/6/23 10:55 GalenGao Exp $$
// */
//@Configuration
//@RequiredArgsConstructor
//public class SecurityConfig extends WebSecurityConfigurerAdapter {
//
//    private final static ObjectMapper objectMapper = new ObjectMapper();
//
//    private final UserDetailsService userDetailsService;
//    private final DataSource dataSource;
//
//    @Autowired
//   private  FindByIndexNameSessionRepository sessionRepository;
//
//
//    @Bean
//    public KaptchaFilter kaptchaFilter() throws Exception {
//        KaptchaFilter kaptchaFilter = new KaptchaFilter();
//        // 设置登陆过滤器url
//        kaptchaFilter.setFilterProcessesUrl("/doLogin");
//        // 设置过滤器的认证器，必须指定否则会报 AuthenticationManager not specified 的异常
//        kaptchaFilter.setAuthenticationManager(authenticationManagerBean());
//        kaptchaFilter.setRememberMeServices(rememberMeServices());
//        // 设置认证失败的逻辑
//        kaptchaFilter.setAuthenticationFailureHandler((request, response, exception) -> {
//            response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
//            Map<String, Object> resp = new HashMap<>();
//            resp.put("code", 500);
//            resp.put("msg", "登陆失败：" + exception.getMessage());
//            // 将登陆成功消息返回给前端
//            response.getWriter().write(objectMapper.writeValueAsString(resp));
//        });
//        // 设置认证失败的逻辑
//        kaptchaFilter.setAuthenticationSuccessHandler((request, response, authentication) -> {
//            response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
//            Map<String, Object> resp = new HashMap<>();
//            resp.put("code", 200);
//            resp.put("msg", "登陆成功");
//            resp.put("authentication", authentication);
//            // 将登陆成功消息返回给前端
//            response.getWriter().write(objectMapper.writeValueAsString(resp));
//        });
//        return kaptchaFilter;
//    }
//
//    /**
//     * 将工厂内部的AuthenticationManager暴露给Spring容器，这样可以在其他对方注入此对象
//     *
//     * @return AuthenticationManager
//     * @throws Exception Exception
//     */
//    @Override
//    @Bean
//    public AuthenticationManager authenticationManagerBean() throws Exception {
//        return super.authenticationManagerBean();
//    }
//
//    /**
//     * 为AuthenticationManager设置userDetailsService对象
//     *
//     * @param auth AuthenticationManagerBuilder
//     * @throws Exception Exception
//     */
//    @Override
//    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//        auth.userDetailsService(userDetailsService);
//    }
//
//    /**
//     * 为spring security进行配置
//     *
//     * @param http http
//     * @throws Exception Exception
//     */
//    @Override
//    protected void configure(HttpSecurity http) throws Exception {
//        http.authorizeHttpRequests()
//                .antMatchers("/index", "/login.html", "/verify.jpg")
//                .permitAll()
//                .anyRequest()
//                .authenticated()
//                .and()
//                .formLogin()
////                .loginPage("/login.html")
////                .loginProcessingUrl("/doLogin")
//                .defaultSuccessUrl("/helloWorld",true)
////                .usernameParameter("username")
////                .passwordParameter("password")
//                .and().rememberMe()
//                .rememberMeServices(rememberMeServices())
//                .tokenRepository(persistentTokenRepository())
//                .and().csrf().disable()
//                .sessionManagement().maximumSessions(1).maxSessionsPreventsLogin(true).
//                sessionRegistry(sessionRegistry()).
//                expiredSessionStrategy(event -> {
//                    HttpServletResponse response = event.getResponse();
//                    response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
//                    Map<String,Object> map = new HashMap<>();
//                    map.put("code",403);
//                    map.put("msg","当前session会话已过期，请重新登录！");
//                    response.getWriter().write(objectMapper.writeValueAsString(map));
//                    response.flushBuffer();
//                })
//              ;
//
//        http.addFilterAt(kaptchaFilter(), UsernamePasswordAuthenticationFilter.class);
//    }
//
//    @Bean
//    public SpringSessionBackedSessionRegistry sessionRegistry(){
//        return new SpringSessionBackedSessionRegistry(sessionRepository);
//    }
//
//
//    /**
//     * 可以监听HttpSession销毁与新建，并将HttpSession创建或者销毁世界进行发布，这样Spring Security就可以感知session创建与销毁了
//     * @return 使用spring-Session-redis共享时候必须注释，否则会与FindByIndexNameSessionRepository冲突
//     */
////    @Bean
////    public HttpSessionEventPublisher httpSessionEventPublisher(){
////        return new HttpSessionEventPublisher();
////    }
//
//    /**
//     * 构建Remember Me service
//     *
//     * @return RememberMeServices
//     */
//    @Bean
//    public RememberMeServices rememberMeServices() {
//        return new MyRememberMe(UUID.randomUUID().toString(), userDetailsService, persistentTokenRepository());
//    }
//
//    /**
//     * 构建持久化TokenRepository
//     *
//     * @return PersistentTokenRepository
//     */
//    @Bean
//    public PersistentTokenRepository persistentTokenRepository() {
//        JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
//        jdbcTokenRepository.setDataSource(dataSource);
//        return jdbcTokenRepository;
//    }
//}
